package com.itcoon.cloud.framework.springdoc.plugin;/**
 * @author Athric Yu
 * 2024/11/12
 **/

import com.itcoon.cloud.framework.config.TemporalPatternConfig;
import com.itcoon.cloud.framework.properties.TemporalPatternConfigProperties;
import com.itcoon.cloud.framework.temporal.AbstractConverter;
import com.itcoon.cloud.framework.utils.TemporalConvertUtils;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.springdoc.core.customizers.ParameterCustomizer;
import org.springframework.core.MethodParameter;

import java.time.temporal.Temporal;

/**
 *
 *
 * @author Athric Yu
 * 2024/11/12
 **/
public class TemporalParameterCustomizer implements ParameterCustomizer, TemporalCustomizer {

    private final TemporalPatternConfigProperties temporalPatternConfigProperties;

    public TemporalParameterCustomizer(TemporalPatternConfigProperties temporalPatternConfigProperties) {
        this.temporalPatternConfigProperties = temporalPatternConfigProperties;
    }

    @Override
    public Parameter customize(Parameter parameterModel, MethodParameter methodParameter) {
        Class<?> parameterType = methodParameter.getParameterType();
        if(Temporal.class.isAssignableFrom(parameterType)){
            Schema schema = new Schema<>();
            TemporalPatternConfigProperties.TemporalSerialization temporalSerialization = TemporalConvertUtils.getTemporalSerialization((Class<? extends Temporal>) parameterType);
            if(Long.class.equals(temporalSerialization.getSerialType())){
                schema.setType("number");
            }
            if(String.class.equals(temporalSerialization.getSerialType())){
                schema.setType("string");
            }
            if(parameterModel.getRequired()){
                Temporal temporal = TemporalConvertUtils.getInstance((Class<? extends Temporal>) parameterType);
                AbstractConverter<?, Temporal> abstractConverter = TemporalPatternConfig.getConverter(temporalSerialization.getSerialType(), temporalSerialization.getTemporalType());
                Object example = abstractConverter.format(temporal);
                schema.setExample(example);
            }
            parameterModel.setSchema(schema);
        }
        return parameterModel;
    }
}
